package cn.jishiyu11.xeqb.fragment

import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.View
import cn.jishiyu11.xeqb.EntityClass.FragmengData.PersonCenter_ControlData

import com.umeng.analytics.MobclickAgent

import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.activity.LogoActivity
import cn.jishiyu11.xeqb.activity.personalCenterActivitys.*
import cn.jishiyu11.xeqb.activity.personalCenterActivitys.AboutUsActivity
import cn.jishiyu11.xeqb.base.BaseFragment
import cn.jishiyu11.xeqb.http.http.i.DataCallBack
import cn.jishiyu11.xeqb.http.http.i.httpbase.*
import cn.jishiyu11.xeqb.utils.*
import cn.jishiyu11.xeqb.webview.X5WebViewActivity
import com.google.gson.Gson
import com.meiqia.meiqiasdk.util.MQIntentBuilder
import kotlinx.android.synthetic.main.fra_personalcenterfragment.*
import okhttp3.Request
import org.json.JSONObject
import java.io.IOException

/**
 * 个人中心
 */
class PersonalCenter_Fragment : BaseFragment, View.OnClickListener,DataCallBack{

    private var token = ""

    override fun requestFailure(request: Request, name: String, e: IOException) {
        if (name.equals("PERSONALCENTER_FRAGMENT_DATA") || name.equals("VIP_DAY_RESIDUE")){
            activity.showShortToast(getString(R.string.quest_net_error))
         }
    }

    override fun requestSuccess(result: String, name: String) {
        when(name){
            "PERSONALCENTER_FRAGMENT_DATA" ->{
                var personalControl =  Gson().fromJson(result,PersonCenter_ControlData::class.java)
                if (personalControl.code.equals("200")){
                    IsViewVisi(frg_vip_member,personalControl.data.but1,personalControl.data.url1)
                    IsViewVisi(frg_gathering_history,personalControl.data.but2,personalControl.data.url2)
                    IsViewVisi(card_manager,personalControl.data.but3,personalControl.data.url3)
                    IsViewVisi(frg_voucher,personalControl.data.but4,personalControl.data.url4)
                    IsViewVisi(frg_return_money,personalControl.data.but5)
                    IsViewVisi(frg_invite_friends,personalControl.data.but6)
                    IsViewVisi(frg_customer_service,personalControl.data.but7)
                    IsViewVisi(set_up_about,personalControl.data.but8)
                    IsViewVisi(set_up_message_center,personalControl.data.but9)
                }
            }
            "VIP_DAY_RESIDUE" ->{
              var   objects = JSONObject(result)
                if (result.contains("reqData")) {
                    var data = objects.get("reqData").toString()
                    var key = token.substring(16, 32)
                    var keydCode = AESUtils.decrypt(key, data)//解密
                    objects = JSONObject(keydCode)
                    objects = JSONObject(objects.getString("reqData"))

                    if (objects.get("code").equals("200")) {
                        var objectdata: JSONObject = objects.get("data") as JSONObject

                        if (!objectdata.getString("closeTime").isNullOrEmpty()) {

                            var vipDays = objectdata.getString("closeTime")
                            var time = makeLong4Date(vipDays)
                            frg_vip_member_content.text = "VIP到期时间: $time"
                        }
                    }
                }
            }
        }

    }

    override val layout: Int
        get() = R.layout.fra_personalcenterfragment

    var isIdCard: String? = null

    constructor() : super() {}

    /**
     * 等rootView加载完后 可以在onViewCrateed中对子view直接调用
     * */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        personal_center_title.text = getString(R.string.name_personal_center)
        personcenter_setting.setOnClickListener { startActivity(Intent(activity, SettingActivity::class.java)) }
//        getButtonIsVisibily()
        initView()
    }

    override fun initView() {

        personal3_head_layout.setOnClickListener(this)

//        frg_vip_member.setOnClickListener(this)
//        frg_gathering_history.setOnClickListener(this)
//        card_manager.setOnClickListener(this)
//        frg_voucher.setOnClickListener(this)
        frg_return_money.setOnClickListener(this)
        frg_invite_friends.setOnClickListener(this)
        frg_customer_service.setOnClickListener(this)
        set_up_about.setOnClickListener(this)
        set_up_message_center.setOnClickListener(this)
        frg_personalcenter_realname.setOnClickListener(this)


        set_up_message_center_qrcode.setOnClickListener(this)

    }

    override fun onClick(v: View) {
        when (v) {

        //个人信息
            personal3_head_layout -> {
                if (USER_UserNo.isNullOrEmpty()){
                    activity.newIntent<LogoActivity>()
                }else{
                    activity.newIntent<PersonalAccount>()
                }
            }

        //Vip
            frg_vip_member -> {
                activity.newIntent<VIPMember>()
//                activity.newIntent<X5WebViewActivity>()
            }

        //收款记录
            frg_gathering_history -> {
//                activity.newIntent<GatheringHistoryActivity>()
            }

        //卡片管理
            card_manager -> {
//                startActivity(Intent(activity, CardManager::class.java))
            }

//        //抵扣券
            frg_voucher -> {
//
//                val url  = "http://img.jishiyu007.com/upload/invite01.png"
//                var intent = Intent(activity,X5WebViewActivity::class.java)
//                intent.putExtra("url",url)
//                startActivity(intent)

            }

        //返现账户
            frg_return_money -> {
            }

        //邀请好友
            frg_invite_friends -> {
                activity.newIntent<InviteFriends>()
            }

        //客服
            frg_customer_service -> {
                var clientInfo = HashMap<String, String>()
                clientInfo.put("name", USER_UserNo)
                clientInfo.put("avatar", "https://s3.cn-north-1.amazonaws.com.cn/pics.meiqia.bucket/1dee88eabfbd7bd4")
                clientInfo.put("id", USER_UserNo)
                clientInfo.put("source", "android  ${getString(R.string.app_name)}")
                var intent = MQIntentBuilder(activity).setCustomizedId(USER_PhoneNo)
                        .setClientInfo(clientInfo)
                        .build()
                startActivity(intent)
            }

        //关于我们
            set_up_about -> {
                activity.newIntent<AboutUsActivity>()
            }

        //消息中心
            set_up_message_center -> {
                activity.newIntent<MessageCenter>()
//                showShare(activity,getString(R.string.app_name),"","这是内容！！",null,null)

            }

        //去实名
            frg_personalcenter_realname -> {
                if (isIdCard.equals("0") && !USER_PhoneNo.isNullOrEmpty()) {
                    activity.newIntent<RealNameActivity>()
                }
            }

            //二维码
            set_up_message_center_qrcode -> {

//                SDCardUtils.saveFileToPublicDirectory()

                activity.showShare("卡小咪的分享"
                        ,"http://f4.market.xiaomi.com/download/AppStore/0237f14901e9a447725207e37ffa5f63b50888c09/cn.jishiyu11.xeqb.apk"
                        ,"来自卡小咪的分享"
                        , BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher )
                ,""
                        ,""
                )

//                IntentIntegrator(activity)
//                        .setOrientationLocked(false)
//                        .setCaptureActivity(QRCodeScanActivity::class.java)
//                        .initiateScan()

//                activity.newIntent<VipPayActivity>()

            }
        }
    }

    fun getButtonIsVisibily(){
        OkHttpManager.getAsync(PENSER_CENTER_BOOLEAN,"PERSONALCENTER_FRAGMENT_DATA",this)
    }

    private fun getUserVipDays() {
        var map = java.util.HashMap<String, Any>()
        var postMap = java.util.HashMap<String, Any>()
        map.put(getString(R.string.userNo), USER_UserNo)
        map.put(getString(R.string.phoneNo), USER_PhoneNo)
        getPostMap2(activity,  map, postMap)
        token = postMap.get("token").toString()
        OkHttpManager.postAsync(VIP_DAY_RESIDUE,"VIP_DAY_RESIDUE",postMap,this)
    }

    /**
     * 对手机号中间四位进行遮盖处理
     * */
    fun dispostPhoneNo(no: String?): String {
        return no?.substring(0, 3) + "****" + no?.substring(no?.length - 4, no?.length)
    }


    override fun onResume() {
        super.onResume()
        getButtonIsVisibily()//按钮显示隐藏接口
        getUserVipDays()//获取VIP剩余天数
        isIdCard = SharedPreferencesUtils.get(activity, getString(R.string.personalcenter_isrealname), "0").toString()
        if (isIdCard.equals("1")) {
            frg_personalcenter_realname.text = "已认证"
            frg_personalcenter_realname.background = resources.getDrawable(R.drawable.corner_view_blue)
        } else {
            frg_personalcenter_realname.background = resources.getDrawable(R.drawable.corner_view_grayback)
            frg_personalcenter_realname.text = "未认证"
        }

        println(USER_UserNo)
        if (!USER_UserNo.isNullOrEmpty() && !USER_PhoneNo.isNullOrEmpty()){
            frg_usercenter_userid.text = "ID"+ USER_UserNo
            frg_usercenter_userphone.text = dispostPhoneNo(USER_PhoneNo)
        }

        MobclickAgent.onPageStart("PersonalCenter_Fragment") //统计页面，"MainScreen"为页面名称，可自定义
    }



    override fun onViewStateRestored(savedInstanceState: Bundle?) {
        super.onViewStateRestored(savedInstanceState)

    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            onResume()
        }
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPageEnd("PersonalCenter_Fragment")
    }


    fun IsViewVisi(v: View,code:String,url:String){

        if (code.equals("1")){
            v.visibility = View.VISIBLE
        }else{
            v.visibility = View.GONE
        }

        if (!url.isNullOrEmpty() && url.contains("http")) {
            v.visibility = View.VISIBLE

            when(v){
                frg_vip_member ->{
                    v.setOnClickListener {
                        var intent = Intent(activity, VIPMember::class.java)
                        intent.putExtra("url", url)
                        activity.startActivity(intent)
                    }
                }

                else->{
                    v.setOnClickListener {
                        var intent = Intent(activity, X5WebViewActivity::class.java)
                        intent.putExtra("url", url)
                        activity.startActivity(intent)
                    }
                }

            }
        }
    }
    fun IsViewVisi(v: View,code:String){

        if (code.equals("1")){
            v.visibility = View.VISIBLE
        }else{
            v.visibility = View.GONE
        }
    }


}
